// 实现这个项目的构建任务
const {src, dest, watch, series, parallel} = require('gulp')
const del = require('del')

const sass = require('gulp-sass')(require('sass'));
const babel = require('gulp-babel');
// const imagemin = require('gulp-imagemin');
const swig = require('gulp-swig');
const ifg = require('gulp-if');
const useref = require('gulp-useref');
const uglify = require('gulp-uglify');
const cleanCss = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin')

const gulpLoadPlugins = require('gulp-load-plugins');
const plugs = gulpLoadPlugins()

const browserSync = require('browser-sync')
const bs = browserSync.create()

const data = require('./package.json')

const style = () => {
  return src('src/assets/styles/*.scss')
  .pipe(sass({outputStyle: 'expanded'}))
  .pipe(dest('dist/css'))
}

const js = () => {
  return src('src/assets/scripts/*.js')
  .pipe(babel({presets: ['@babel/preset-env']}))
  .pipe(dest('dist/js'))
}

const img = () => {
  return src('src/assets/images/**')
  // .pipe(imagemin())
  .pipe(dest('dist/img'))
}

const font = () => {
  return src('src/assets/fonts/**')
  // .pipe(imagemin())
  .pipe(dest('dist/font'))
}

const extra = () => {
  return src('public/**').pipe(dest('dist/public'))
}

const html = () => {
  return src(['src/*.html', 'src/layouts/*.html', 'src/partials/*.html'])
  .pipe(swig())
  .pipe(dest('dist'))
}

const clean = () => {
  return del('dist')
}

const server = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', js)
  watch(['src/assets/fonts/**', 'src/assets/images/**'], bs.reload)

  bs.init({
    notify: false,
    files: 'dist',
    server: {
      baseDir: ['dist', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const ref = () => {
  return src('dist/*html')
  .pipe(useref({searchPath:['dist', '.']}))
  .pipe(ifg(/\.js$/, uglify()))
  .pipe(ifg(/\.html$/, htmlmin({collapseWhitespace: true, minifyCSS: true, minifyJS: true})))
  .pipe(ifg(/\.css$/, cleanCss()))
  .pipe(dest('dist'))
}

const develop = series(parallel(style, js, html), ref, server)
const build = series(clean, parallel(style, js, html, img, extra, font))

module.exports = {
  clean,
  develop,
  build
}